// 分类路由
const express = require("express");
// 引入connect-multiparty中间件
var multipart = require("connect-multiparty");
// 创建中间件对象
var multipartMiddleware = multipart();
// 引入数据库配置
const db = require("../mysql");
// 创建路由对象
const category = express.Router();

// 获取所有分类
category.get("/getCategory", multipartMiddleware, (req, res) => {
  const sqlStr = `select * from category`;
  db.query(sqlStr, (err, results) => {
    if (err) return res.json({ status: 404, message: error });
    res.json({ status: 200, data: results });
  });
});

// 模糊搜索分类
category.get("/getCategoryByName", multipartMiddleware, (req, res) => {
  const sqlStr = `select * from category where category_name like '%${req.query.query}%'`
  db.query(sqlStr, (err, results) => {
    if (err) return res.json({ code: 400, message: error });
    res.json({ code: 200, data: results });
  });
})

// 添加分类
category.post("/addCategory", multipartMiddleware, (req, res) => {
  const sqlStr = `insert into category (category_name,category_update) values ('${req.body.category_name}','${req.body.category_update}')`
  db.query(sqlStr, (err, results) => {
    if (err) return res.json({ code: 400, message: error });
    res.json({ code: 200, message: '添加分类成功' });
  });
})

// 根据id获取分类
category.get("/getCategoryById/:categoryId", multipartMiddleware, (req, res) => {
  const sqlStr = `select * from category where category_id = '${req.params.categoryId}'`
  db.query(sqlStr, (err, results) => {
    if (err) return res.json({ code: 400, message: error });
    res.json({ code: 200, data: results });
  });
})


// 修改分类
category.put("/updateCategory", multipartMiddleware, (req, res) => {
  const sqlStr = `update category set category_name='${req.body.category_name}',category_update='${req.body.category_update}' where category_id='${req.body.category_id}'`
  db.query(sqlStr, (err, results) => {
    if (err) return res.json({ code: 400, message: '修改分类失败' });
    res.json({ code: 200, message: '修改分类成功' });
  });
})

// 删除分类
category.post("/deleteCategory", multipartMiddleware, (req, res) => {
  const sqlStr = `delete from category where category_id = '${req.body.category_id}'`
  db.query(sqlStr, (err, results) => {
    if (err) return res.json({ code: 400, message: '删除分类失败' });
    res.json({ code: 200, message: '删除分类成功' });
  });
})
module.exports = category;
